from flask import request
from flask_wtf.file import FileRequired, FileAllowed
from wtforms import Form, FileField
from wtforms.compat import iteritems
from app.libs.error_code import ParameterException


class FileBaseForm(Form):
    def __init__(self):
        #data = request.get_json(silent=True)
        data = request.files.to_dict()
        args = request.form.to_dict()
        super(FileBaseForm, self).__init__(data=data, **args)

    def validate_for_api(self):
        valid = super(FileBaseForm, self).validate()
        if not valid:
            raise ParameterException(msg=self.errors)
        return self

    @property
    def errors(self):
        # if self._errors is None:
        #     self._errors = dict((name, f.errors) for name, f in iteritems(self._fields) if f.errors)
        _form_errors = []
        if self._errors is None:
            for name, f in iteritems(self._fields):
                if f.errors:
                    for item in f.errors:
                        _form_errors.append(item)
        return _form_errors


class FileManualPullRefundForm(FileBaseForm):
    csv_file = FileField('file', validators=[FileRequired(message='请选择文件上传'), FileAllowed(['csv'], message='仅允许上传csv格式文件！')])

    def validate_csv_file(self, field):
        file_name = field.data.filename
        field.data.save('app/alipay/bill/csv/'+file_name)
